<?php
require_once '../config.php'; 
require_once '../admin_check.php';

// 获取要编辑的用户ID
$user_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$user_id) {
    $_SESSION['errors'] = ["无效的用户ID"];
    header('Location: index.php');
    exit;
}

// 获取用户当前信息
try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();

    if (!$user) {
        $_SESSION['errors'] = ["用户不存在"];
        header('Location: index.php');
        exit;
    }
} catch (PDOException $e) {
    die("数据库错误: " . $e->getMessage());
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = clean_input($_POST['username']);
    $email = clean_input($_POST['email']);
    $role = $_POST['role'];
    $new_question = clean_input($_POST['security_question']);
    $new_answer = clean_input($_POST['security_answer']);

    $errors = [];
    
    try {
        // 基础验证
        if (empty($username)) $errors[] = '用户名不能为空';
        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = '邮箱格式无效';
        if (!in_array($role, ['user', 'admin'])) $errors[] = '无效的角色类型';

        // 检查用户名冲突
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
        $stmt->execute([$username, $user_id]);
        if ($stmt->rowCount() > 0) $errors[] = '用户名已存在';

        // 检查邮箱冲突
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $stmt->execute([$email, $user_id]);
        if ($stmt->rowCount() > 0) $errors[] = '邮箱已被使用';

        // 密保问题验证
        if (!empty($new_question)) {
            if (empty($new_answer)) {
                $errors[] = '修改密保问题必须提供答案';
            } elseif (strlen($new_answer) < 2) {
                $errors[] = '安全答案至少需要2个字符';
            }
        }

        if (empty($errors)) {
            // 构建更新参数
            $update_fields = [
                'username = ?',
                'email = ?',
                'role = ?'
            ];
            $params = [$username, $email, $role];

            // 处理密保问题修改
            if (!empty($new_question)) {
                $answer_hash = password_hash(
                    mb_strtolower(trim($new_answer)), 
                    PASSWORD_DEFAULT
                );
                $update_fields[] = 'security_question = ?';
                $update_fields[] = 'security_answer_hash = ?';
                $params[] = $new_question;
                $params[] = $answer_hash;
            }

            // 禁止修改当前管理员角色
            if ($user_id == $_SESSION['user_id'] && $role != 'admin') {
                throw new Exception('不能修改自己的管理员身份');
            }

            // 执行更新
            $sql = "UPDATE users SET " . implode(', ', $update_fields) . " WHERE id = ?";
            $params[] = $user_id;

            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);

            $_SESSION['success'] = '用户信息更新成功';
            header('Location: index.php');
            exit;
        }
    } catch (Exception $e) {
        $errors[] = $e->getMessage();
    }
    
    $_SESSION['errors'] = $errors;
}

include '../includes/header.php';
?>

<div class="container mt-4">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h4>编辑用户：<?= htmlspecialchars($user['username']) ?></h4>
            <a href="index.php" class="btn btn-secondary">返回列表</a>
        </div>
        <div class="card-body">
            <!-- <?php include '../includes/alerts.php'; ?> -->

            <form method="post">
                <!-- 基础信息 -->
                <div class="row g-3 mb-4">
                    <div class="col-md-6">
                        <label class="form-label">用户名</label>
                        <input type="text" 
                               class="form-control" 
                               name="username" 
                               value="<?= htmlspecialchars($user['username']) ?>" 
                               required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">电子邮箱</label>
                        <input type="email" 
                               class="form-control" 
                               name="email" 
                               value="<?= htmlspecialchars($user['email']) ?>" 
                               required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">账户角色</label>
                        <select class="form-select" 
                                name="role" 
                                <?= ($user['id'] == $_SESSION['user_id']) ? 'disabled' : '' ?>>
                            <option value="user" <?= $user['role'] === 'user' ? 'selected' : '' ?>>普通用户</option>
                            <option value="admin" <?= $user['role'] === 'admin' ? 'selected' : '' ?>>管理员</option>
                        </select>
                        <?php if ($user['id'] == $_SESSION['user_id']): ?>
                            <input type="hidden" name="role" value="admin">
                        <?php endif; ?>
                    </div>
                </div>

                <!-- 密保信息 -->
                <div class="border-top pt-4">
                    <h5 class="mb-3">安全设置</h5>
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">当前密保问题</label>
                            <input type="text" 
                                   class="form-control" 
                                   value="<?= htmlspecialchars($user['security_question']) ?>" 
                                   readonly>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">新密保问题（可选）</label>
                            <input type="text" 
                                   class="form-control" 
                                   name="security_question" 
                                   placeholder="留空表示不修改">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">新问题答案</label>
                            <input type="text" 
                                   class="form-control" 
                                   name="security_answer" 
                                   placeholder="修改问题时必须填写">
                            <small class="form-text text-muted">答案将被加密存储</small>
                        </div>
                    </div>
                </div>

                <div class="mt-4">
                    <button type="submit" class="btn btn-primary">保存更改</button>
                    <a href="index.php" class="btn btn-outline-secondary">取消</a>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include '../includes/footer.php'; ?>